import { request, calcScrollViewHeight, WXShowModal, WXNavigateTo } from '../../utils/index.js';
import { Api, delCartGood, editCartCount } from '../../config/api.js';

var appInst = getApp();

Page({
  data: {
    tabbar: {},
     isIphoneX:null,
    host: appInst.globalData.host,
    cart: [],
    checkAll: true,
    totalMoney: 0,
    goodCount: 0,
    scrollViewHeight: 0,
    radioColor: appInst.globalData.color.goldLight
  },


  onLoad: function (options) {
        const token = wx.getStorageSync("token")
        if (!token) {
            wx.reLaunch({
                url: '/pages/login/login'
            });
        }

      appInst.editTabbar(); //调用tabbar
      this.getMyCart();
  },
  onShow() {
  },

 onReady: function () {
     this.setData({
         isIphoneX: appInst.globalData.systemInfo.model.search('iPhone X') != -1 ? true : false
     })
 },

  // 获取我的购物车
  getMyCart() {
    request({ url: Api.getMyCart })
      .then(res => {
        this.setData({ cart: res.data.data.map(item => ({ ...item, select: true })) })
        // 计算总价
        this.calcTotalMoney()
        this.calcScrollViewHeight();
      })
      .catch(err => { });
  },
  // 计算 scroll-view 高度
  calcScrollViewHeight() {
    const otherElArr = ['#handler']
    calcScrollViewHeight(otherElArr, this, 12).then(res => {
      this.setData({ scrollViewHeight: res })
    })
  },

  // 切换商品选中
  handleRadioTap(e) {
    const { goodid } = e.currentTarget.dataset
    let cart = this.data.cart
    let isCheckAll = true

    cart.forEach(item => {
      if (item.id === goodid) {
        item.select = !item.select
      }

      if (!item.select) {
        isCheckAll = false
      }
    })

    this.setData({ checkAll: isCheckAll, cart })
    this.calcTotalMoney()
  },


  // 全选
  handleCheckAll() {
    let cart = this.data.cart
    let nowCheckAll = !this.data.checkAll

    this.setData({
      checkAll: nowCheckAll,
      cart: cart.map(item => ({ ...item, select: nowCheckAll }))
    })

    this.calcTotalMoney()
  },
  // 计算总价和商品数量
  calcTotalMoney() {
    let totalMoney = 0
    let goodCount = 0

    this.data.cart.forEach(item => {
      if (item.select) {
        totalMoney += +item.price * item.num
        goodCount += item.num
      }
    })

    this.setData({ totalMoney, goodCount })
  },
  // 增减数量
  handleChangeCount(e) {
    const { step, goodid } = e.currentTarget.dataset
    const good = this.data.cart.find(item => item.id === goodid)

    if (step < 0) {
      if (good.num === 1) {
        WXShowModal('提示', '您想要从购物车中删除该商品吗？').then(res => {
          if (res.confirm) {
            // 删除 ajax
            this._delCartGood(good.id)
          }
        })
      } else {
        // 减数量 ajax
        this._editCartCount(good.id, +good.num + step)
      }
    } else {
      // 加数量 ajax
      this._editCartCount(good.id, +good.num + step)
    }
  },

//   结算
  placeOrder() {
    let goodlist = []
    this.data.cart.filter((item)=>{
        if (item.select){
            goodlist.push(item)
        }
    })
    wx.setStorageSync('goodlist', goodlist);
    wx.setStorageSync('gmtype', 2) //1 商品立即购买
    WXNavigateTo('/pages/place_order/place_order')
  },


  _editCartCount(goodid, num) {
    editCartCount(goodid, num).then(res => {
      // 更新 data.cart
      this.setData({
        cart: this.data.cart.map(item => {
          if (item.id === goodid) {
            return { ...item, num }
          }
          return item
        })
      })

      // 重新计算总计
      this.calcTotalMoney()
    }).catch(err => { })
  },

//   删除购物车数据
  _delCartGood(goodid) {
    delCartGood(goodid).then(res => {
      this.setData({
        cart: this.data.cart.filter(item => item.id !== goodid)
      })

      this.calcTotalMoney()
    }).catch(err => { })
  }
});
